#!/usr/bin/perl

#===============================================================================
#     REVISION:  $Id$
#  DESCRIPTION:  Test for Meter::Sessions
#===============================================================================

use strict;
use warnings;

use Readonly;
Readonly our $VERSION => qw($Revision$) [1];

use English qw( -no_match_vars );

#use Smart::Comments;
#$ENV{'DONT_CLEANUP'} = 1;

use Meter::Test qw(
    init_tmp_db
);

use Meter::Users;
use Meter::Sessions;

use Meter::Utils qw(
    dump_compact
);

use Test::More tests => 7;
use Test::Exception;
use Test::DatabaseRow;

Readonly my $USERNAME => 'user1';
Readonly my $EMAIL    => 'email1@example.com';
Readonly my $PASSWORD => '123456';

Readonly my $SESSION_ID                 => '823af87f57ed4e5e7d7934ee09c68d57';
Readonly my $LAST_ACTIVITY_DATETIME     => '20110707T214510+0400';
Readonly my $NEW_LAST_ACTIVITY_DATETIME => '20110707T224510+0400';

sub _create_user {
    my $user = Meter::Users->insert(
        {   username => $USERNAME,
            password => $PASSWORD,
            email    => $EMAIL,
        }
    );

    return $user;
}

sub test_common_case {
    my $session_fields = {
        session_id             => $SESSION_ID,
        last_activity_datetime => $LAST_ACTIVITY_DATETIME,
    };

    # create session
    lives_ok {
        Meter::Sessions->insert(
            {   user => _create_user(),
                %{$session_fields},
            }
        );
    }
    'Create new session ' . dump_compact( $session_fields, 'SESSION' );

    row_ok(
        table => 'sessions',
        where => [ %{$session_fields} ],
        label => 'Check database row for new session '
            . dump_compact( $session_fields, 'SESSION' ),
    );

    # retrieve session
    my $session = Meter::Sessions->retrieve($SESSION_ID);
    ok( $session, "Retrieve session '$SESSION_ID'" );

    # update session
    my $updated_session_fields = {
        %{$session_fields},
        last_activity_datetime => $NEW_LAST_ACTIVITY_DATETIME,
    };

    lives_ok {
        $session->last_activity_datetime($NEW_LAST_ACTIVITY_DATETIME);
        $session->update();
    }
    'Update session ' . dump_compact( $updated_session_fields, 'SESSION' );

    row_ok(
        table => 'sessions',
        where => [ %{$updated_session_fields} ],
        label => 'Check database row for updated session '
            . dump_compact( $updated_session_fields, 'SESSION' ),
    );

    # delete session
    lives_ok {
        $session->delete();
    }
    'Delete session';

    not_row_ok(
        table => 'sessions',
        where => [ session_id => $SESSION_ID ],
        label => "Check NO database row for deleted session '$SESSION_ID'",
    );

    return;
}

sub run_tests {
    init_tmp_db();

    test_common_case();

    return;
}

run_tests();
